import { FormProps } from "@/components/modal/form.modal"
import { Field_FormSave } from "@/components/utils/field.list"
import { FileExtMeta, FormRender, FormUpload } from "@whzhuke/antd"
import React, { useCallback } from "react"
import useForm from "antd/es/form/hooks/useForm"
import baseSystem from "@/services/base.system"
import customsService from "@/services/customs.service"

export const UploadTemplate: React.FC<FormProps & { type?: keyof typeof FileExtMeta; values?: any }> = props => {
  const { onDone, type = "documentImage", values } = props
  const [form] = useForm<any>()

  const onFinish = useCallback(
    (data: any) => {
      const { fileUrl } = data
      if (!fileUrl) {
        return
      }

      // 从 values 获取合同ID
      const contractId = values?.contractId
      if (!contractId) {
        console.error("缺少合同ID")
        return
      }

      // 调用服务保存模板，传递 fileUrl 和 contractId
      customsService
        .save({ fileUrl, contractId })
        .then(res => {
          onDone?.()
        })
        .catch(error => {
          console.error("上传模板失败:", error)
        })
    },
    [onDone, values]
  )

  return (
    <FormRender
      form={form}
      layout="horizontal"
      preserve={false}
      onFinish={onFinish}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ width: 600 }}
      fieldList={[
        {
          fieldType: "diy",
          formItemConfig: {
            name: "fileUrl",
            label: "文件",
            required: true,
            rules: [{ required: true, message: "请上传导入文件" }],
            normalize: v => v[0]
          },
          component: <FormUpload apiService={baseSystem.upload} accept={FileExtMeta[type].toString()} allowFile={type} assetKey="public" />
        },
        { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
      ]}
      autoComplete="off"
    />
  )
}
